package fun.lifepoem.notification;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author Yiwyn
 * @create 2022/7/6 21:28
 */
@Service
public class EmailNotificationService {


    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String formName;


    public void SendEmail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(formName);
        simpleMailMessage.setTo("5597104@qq.com");
        simpleMailMessage.setSubject("Java技术栈投稿");
        simpleMailMessage.setText("技术分享");
        javaMailSender.send(simpleMailMessage);
    }

    public void SendTemaplateEmail() throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setFrom(formName);
        mimeMessageHelper.setTo("5597104@qq.com");
        mimeMessageHelper.setSubject("Java技术栈投稿");

        Context context = new Context();
        context.setVariable("username", "yiwyn");

        String content = templateEngine.process("email.html", context);
        mimeMessageHelper.setText(content, true);
        javaMailSender.send(mimeMessage);
    }


}
